/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#ifndef MK_TIMER_H
#define MK_TIMER_H
#include "MkUtil/MkTime.h"
#include "MkUtil/MkRwLock.h"
#include "MkUtil/MkThread.h"

//if want to kill timer you can return not NonError
typedef MkFunction<void()>   DelayerCallback;
class MkApi CMkTimer
{
public:
    typedef struct _delayer_param
    {
        DelayerCallback Cb;
        Uint32          MilliSecDelay;
        CMkTime         ActiveTime;
        BOOL            bTimer;
        _delayer_param()
        {
            Cb = nullptr;
            MilliSecDelay = 0;
            bTimer = FALSE;
        }
    }MkDelayerParam;
public:
    CMkTimer();
    ~CMkTimer();
    Uint32 StartTimerThread();
    Uint32 StopTimerThread();
    Uint32 AddDelayer(const DelayerCallback Cb, Uint32 MilliSecDelay, INOUT MkString& DelaySession);
    Uint32 AddTimer(const DelayerCallback Cb, Uint32 MilliSecInterval, INOUT MkString& TimerSession);
    Uint32 DeleteTimer(const MkString& TimerSession);
    Uint32 DeleteDelayer(const MkString& DelaySession);
    Uint32 ActiveDelayer(const MkString& DelaySession);
    Uint32 ActiveTimer(const MkString& TimerSession);
    Uint32 ChangeDelayerDelayTime(const MkString& DelaySession, Uint32 MilliSecDelay);
    Uint32 ChangeTimerInterval(const MkString& TimerSession, Uint32 MilliSecInterval);

    Uint32 Dispatch();
    Uint32 LoopBreak();
    Uint32 GetScore();
protected:
    void LoopDelayer();
private:
    void AddWaitMilliSec(const CMkTime& NowTime, Uint32 WaitMillSec);
private:
    CMkThread                           m_TimerThread;
    CMkTime                             m_NextActiveTime;
    CMkRwLock                           m_DelayerLock;
    MkMap<MkString, MkDelayerParam>     m_MapDelayer;
    BOOL                                m_bRun;
    void*                               m_WaitEvent;
    void*                               m_WaitThreadStartEvent;
    BOOL                                m_bHasDelete;
    CMkRwLock                           m_WaitTimeLock;
    MkList<std::pair<CMkTime, Uint32>>  m_WaitTimeList;
};



#endif


